﻿using MediatR;
using MS.Data.API.Read.Command;
using MS.Data.Domain;
using MS.Data.ErrorCode;
using MS.Data.Infratructrue.Istanbul;

namespace MS.Data.API.Read.CommandHandle
{
    /// <summary>
    /// 显示权限列表命令处理
    /// </summary>
    public class GetPermissionCommandHandel : IRequestHandler<GetPermissionCommand, APIResult<APIPing<Permission>>>
    {
        /// <summary>
        /// 权限
        /// </summary>
        IBaseRepository<Permission> perRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="perRep">权限</param>
        public GetPermissionCommandHandel(IBaseRepository<Permission> perRep)
        {
            this.perRep = perRep;
        }
        /// <summary>
        ///  处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回权限列表结果</returns>
        public Task<APIResult<APIPing<Permission>>> Handle(GetPermissionCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPing<Permission>> result = new APIResult<APIPing<Permission>>();
            result.code = APIEnum.显示成功;
            result.mes = APIEnum.显示成功.ToString();

            var list = from a in perRep.GetAll()
                       where !a.IsDel
                       select new Permission()
                       {
                           PermissionId = a.PermissionId,
                           PermissionName = a.PermissionName,
                           PermissionNo = a.PermissionNo,
                           PermissionType = a.PermissionType,
                       };
            if (!string.IsNullOrEmpty(request.PermissionName))
            {
                list=list.Where(s=>s.PermissionName.Contains(request.PermissionName));
            }

            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);

            list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

            APIPing<Permission> page = new APIPing<Permission>()
            {
                totalCount = totalCount,
                pageCount = pageCount,
                pageData = list.ToList(),
            };
            result.data = page;


            return Task.FromResult(result);
        }
    }
}
